package com.zym.init.controller.backend;

import com.zym.init.core.annotation.ApiBackendRestController;
import com.zym.init.core.annotation.Log;
import com.zym.init.core.controller.BaseController;
import com.zym.init.core.domain.AjaxResult;
import com.zym.init.enums.ResourceTypeEnum;
import com.zym.init.core.exception.ServiceException;
import com.zym.init.model.po.ResourcePo;
import com.zym.init.model.query.DirectoryQuery;
import com.zym.init.model.query.ResourceQuery;
import com.zym.init.model.vo.UploadFileVo;
import com.zym.init.core.plugin.storage.StorageDriver;
import com.zym.init.service.ResourceService;
import com.zym.init.core.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Validated
@ApiBackendRestController
public class FileController extends BaseController {

    private final ResourceService resourceService;

    public FileController(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    /**
     * 文件上传
     *
     * @param file     上传的文件
     * @param parentId 父目录ID(可选) 默认0
     * @param path     上传路径(可选)
     */
    @Log(title = "文件上传", isFile = true)
    @PreAuthorize("@ss.hasPermission('system:file:upload')")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, @RequestParam("pId") Long parentId, @RequestParam("path") String path) {
        if (file.isEmpty()) {
            throw new ServiceException("上传文件不能为空");
        }

        Long pId = parentId;

        // 创建文件夹
        if (StringUtils.hasLength(path)) {
           pId = resourceService.createDirectory(parentId, path);
        }

        // 上传文件
        StorageDriver storageDriver = new StorageDriver();
        UploadFileVo fileVo = storageDriver.upload(file);

        // 保存文件信息到数据库
        ResourceQuery query = new ResourceQuery();
        query.setStorageId(fileVo.getStorageId());
        query.setResourceType(ResourceTypeEnum.FILE.getType());
        query.setResourceName(fileVo.getName());
        query.setMediaType(fileVo.getMediaType());
        query.setSize(fileVo.getSize());
        query.setFileExtension(fileVo.getExtension());
        query.setUploadUserId(SecurityUtils.getUserId());
        query.setParentResourceId(null);
        query.setOriginalName(fileVo.getOriginalName());
        query.setPath(fileVo.getUrl());
        query.setParentResourceId(pId);
        resourceService.add(query);

        fileVo.setId(query.getResourceId());
        fileVo.setEncryptionId(resourceService.getEncryptionId(query.getResourceId()));

        return success("上传文件成功", fileVo);
    }

    /**
     * 创建文件夹
     */
    @Log(title = "创建文件夹")
    @PreAuthorize("@ss.hasPermission('system:file:createDir')")
    @PostMapping("/createDir")
    public AjaxResult createDir(@RequestBody DirectoryQuery query) {
        // 获取目录名称
        String directoryName = query.getDirectoryName();
        if (!StringUtils.hasLength(directoryName)) {
            throw new ServiceException("文件夹名称不能为空");
        }

        // 完整目录
        StringBuilder path = new StringBuilder();

        // 拼接父目录路径
        if (query.getParentId() != null && query.getParentId() != 0) {
            ResourcePo po = resourceService.getById(query.getParentId());
            if (po == null) {
                throw new ServiceException("父目录不存在");
            }
            if (!po.getResourceType().equals(ResourceTypeEnum.DIRECTORY.getType())) {
                throw new ServiceException("非法操作，父目录不是文件夹");
            }
            path.append(po.getPath()).append("/");
        }

        // 拼接当前目录名称
        path.append(directoryName);

        // 检查目录是否已经创建
        boolean result = resourceService.checkDirectory(path.toString());
        if (result) {
            throw new ServiceException("目录：" + path + " 已经创建");
        }

        // 读取存储配置
        StorageDriver storageDriver = new StorageDriver();

        // 保存文件信息到数据库
        ResourceQuery rQuery = new ResourceQuery();
        rQuery.setStorageId(storageDriver.getStorageId());
        rQuery.setResourceType(ResourceTypeEnum.DIRECTORY.getType());
        rQuery.setResourceName(directoryName);
        rQuery.setUploadUserId(SecurityUtils.getUserId());
        rQuery.setParentResourceId(query.getParentId());
        rQuery.setPath(path.toString());
        resourceService.add(rQuery);

        return success("创建文件夹成功");
    }
}
